package com.nexgo.payment.trans.setting.terminalkey.dowmtmk;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;

import com.nexgo.oaf.apiv3.SdkResult;
import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.aop.annotation.RunOnMainThread;
import com.nexgo.payment.databases.DataSource;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by wzp on 2018/1/9.
 */

public class TmkDownloadPresenter implements TmkDownloadContract.Presenter{
    private final Context mContext;
    private final TmkDownloadContract.View mView;
    private final DataSource mRepository;
    private final Handler mHandler;
    private TmkDownload mTmkDownload;
    public TmkDownloadPresenter(@NonNull Context context, @NonNull TmkDownloadContract.View view, @NonNull DataSource repository) {
        mContext = context.getApplicationContext();
        mView = checkNotNull(view);
        mRepository = checkNotNull(repository);
        mHandler = new Handler(Looper.getMainLooper());
        mTmkDownload = new TmkDownload(mRepository);
        mView.setPresenter(this);
    }
    @Override
    public void start() {
        postMainThread(() -> mView.setWaitingIndicator(true, null, App.sContext.getString(R.string.doing_something)));
        onStartImportKey();
    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {
        mTmkDownload.cancelLoadKey();
    }

    @Override
    public void onStartImportKey() {
        new Thread(() -> {
            // 交行下秘钥主机超时时间为30秒
            int retCode = mTmkDownload.requestdownTmk(0, 30);
            switch (retCode){
                case SdkResult.Success:
                    postMainThread(() -> mView.setWaitingIndicator(false, null, App.sContext.getString(R.string.doing_something)));
                    postMainThread(() -> mView.showSuccessful());
                    break;
                default:
                    postMainThread(() -> mView.setWaitingIndicator(false, null, App.sContext.getString(R.string.doing_something)));
                    postMainThread(() -> mView.showFail());
                    break;
            }
        }).start();
    }

    @RunOnMainThread
    protected void postMainThread(Runnable runnable) {
        runnable.run();
    }
}
